package club.hicode.daydayup.redis.distribute;

import cn.hutool.core.thread.ThreadUtil;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.concurrent.TimeUnit;

/**
 * 最简答的 lock 方法
 *
 * @author Liu Chunfu
 * @date 2018-06-11 下午4:34
 **/
public class SimpleLock {


    public void lock() {
        RedisCommands<String, String> syncCommands = getStringStringRedisCommands();


        Boolean lock = syncCommands.setnx("lock", "0");
        if (lock) {
            return;
        }
        while (!lock) {
            lock = syncCommands.setnx("lock", "0");
            ThreadUtil.sleep(1, TimeUnit.SECONDS);
        }
    }

    private RedisCommands<String, String> getStringStringRedisCommands() {
        RedisURI redisURI = new RedisURI("alios", 6379, 10 * 1000, TimeUnit.SECONDS);
        RedisClient redisClient = RedisClient.create(redisURI);
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        return connection.sync();
    }


    public void unlock() {
        RedisCommands<String, String> syncCommands = getStringStringRedisCommands();
        Long lock = syncCommands.del("lock");
    }
}
